package com.eqs.enterprisequestionnaire.service;

import java.util.*;
import java.util.stream.Collectors;
import com.eqs.enterprisequestionnaire.model.pojo.Answer;
import com.eqs.enterprisequestionnaire.model.pojo.Option;
import com.eqs.enterprisequestionnaire.model.pojo.Question;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.eqs.enterprisequestionnaire.model.enums.QuestionEnum.isChoiceType;

@Service
public class ChoiceAnalysisService {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private OptionService optionService;

    @Autowired
    private HistoryService historyService;
    public Map<String, Integer> getSelectionCounts(Integer questionId) {
        Question question = questionService.selectByQuestionId(questionId);

        // 判断是否为选择题类型
        if (!isChoiceType(question.getType())) {
            return null;
        }

        // 获取该问题的所有选项
        List<Option> options = historyService.getListOptionByQuestionId(questionId);

        // 初始化选项选取数的Map
        Map<Integer, Integer> optionCountMap = new HashMap<>();
        for (Option option : options) {
            optionCountMap.put(option.getId(), 0);
        }

        // 获取该问题的所有答案
        List<Answer> answers = historyService.getListAnswerByQuestionId(questionId);

        // 计算每个选项的选取次数
        for (Answer answer : answers) {
            String[] selectedOptionIds = answer.getContent().split(",");
            for (String selectedOptionId : selectedOptionIds) {
                int optionId = Integer.parseInt(selectedOptionId.trim());
                optionCountMap.put(optionId, optionCountMap.get(optionId) + 1);
            }
        }

        // 转换为所需的返回格式
        Map<String, Integer> selectionCounts = options.stream()
                .collect(Collectors.toMap(
                        Option::getContent,
                        option -> optionCountMap.get(option.getId()),
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));

        return selectionCounts;
    }
}